package com.noble.meether.fragment.rob.adapter;

import android.app.Activity;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.noble.glamour.bean.center.user.detail.UserDetail;
import com.noble.glamour.module.logic.application.App;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.baseui.LoadingDialog;
import com.noble.library.image.ImageLoader;
import com.noble.library.log.PLogger;
import com.noble.library.log.PToast;
import com.noble.library.permission.PermissionUtil;
import com.noble.library.permission.callback.PermissionListener;
import com.noble.library.widget.RecyclerView.base.BaseRecyclerViewAdapter;
import com.noble.library.widget.RecyclerView.base.BaseRecyclerViewHolder;
import com.noble.meether.MeetUIShow;
import com.noble.meether.R;
import com.noble.meether.chat.ui.agora.RtcUIShow;
import com.noble.meether.chat.ui.agora.model.AgoraConstant;
import com.noble.meether.chat.ui.agora.model.EngineConfig;
import com.noble.meether.chat.ui.agora.util.RtcUtil;
import com.noble.meether.fragment.rob.RobMessage;
import com.noble.meether.fragment.rob.bean.Rob;
import com.noble.meether.fragment.rob.util.RobClickListener;

/**
 * 抢聊Item
 */
public class RobAdapter extends BaseRecyclerViewAdapter<Rob> {
    private Context mContext;
    private boolean permissionAuth;    // 不能抢聊原因
    private boolean isRob = false;    // 是否在抢聊中

    public RobAdapter(Context mContext) {
        this.mContext = mContext;
        permissionAuth = PermissionUtil.getAVAuth();
    }

    @Override
    public int[] getItemLayouts() {
        return new int[]{R.layout.item_rob};//钻石item布局
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return super.onCreateViewHolder(parent, viewType);
    }

    @Override
    public void onBindRecycleViewHolder(BaseRecyclerViewHolder viewHolder, int position) {
        MyViewHolder vh = new MyViewHolder(viewHolder);
        final Rob info = getItem(position);
        ImageLoader.loadCircleAvatar(mContext, info.getAvatar(), vh.user_head);
        vh.user_nick.setText(info.getNickName());

        UserDetail userDetail = ModuleMgr.getCenterMgr().getMyInfo();
        vh.tv_amount.setText(String.valueOf(userDetail.getAmountStar()));
        vh.user_vip.setVisibility(info.isVip() ? View.VISIBLE : View.GONE);

        vh.btn_rob.setOnClickListener(new RobClickListener() {
            @Override
            public void onRobClick(View v) {
                if (isRob) return;

                isRob = true;
                LoadingDialog.show((FragmentActivity) App.getActivity(), "抢夺中...");
                if (ModuleMgr.getRtcEnginMgr().getEngineConfig().isBusy) {
                    PToast.showShort("当前处于聊天中，无法抢聊");
                    LoadingDialog.closeLoadingDialog();
                    isRob = false;
                    return;
                }

                UserDetail myInfo = ModuleMgr.getCenterMgr().getMyInfo();
                if (!myInfo.isPassAuth()) {
                    LoadingDialog.closeLoadingDialog();
                    isRob = false;
                    if (myInfo.getStatusAuth() == -2) {
                        PToast.showShort("认证审核中，请耐心等待！");
                        return;
                    }
                    MeetUIShow.showUserAuthDlg((FragmentActivity) App.getActivity());
                    return;
                }

                if (!permissionAuth) {
                    LoadingDialog.closeLoadingDialog();
                    permissionAuth();
                    isRob = false;
                    return;
                }
                ModuleMgr.getCommonMgr().getUserRelation(info.getUid(), (isOk, status) -> {
                    if (status == -4) {
                        LoadingDialog.closeLoadingDialog();
                        PLogger.d("该用户已把你拉黑，无法抢聊");
                        isRob = false;
                        return;
                    }
                    // 发送抢聊消息
                    RtcUtil.getInstance().resetSynchStatus();
                    startRob(info.getUid(), info.getVcId());
                });
            }
        });
    }

    private void startRob(long uid, long mVcId) {
        ModuleMgr.getRtcChatMgr().reqChatGrab(mVcId, response -> {
            if (!response.isOk()) {
                PToast.showShort(response.getMsg());
                LoadingDialog.closeLoadingDialog();
                isRob = false;
                return;
            }

            ModuleMgr.getRtcEnginMgr().releaseEngineConfig();  // 重置聊天参数
            RobMessage robMessage = new RobMessage();
            robMessage.parseJson(response.getResString());
            EngineConfig config = ModuleMgr.getRtcEnginMgr().getEngineConfig();
            config.isCalling = true;
            config.mChatType = AgoraConstant.RTC_CHAT_VIDEO;
            config.mOtherId = uid;
            config.mChannel = robMessage.getcName();
            config.mVcid = robMessage.getVcId();
            config.mChannelKey = robMessage.getcKey();
            RtcUIShow.showRtcRobVideoAct((Activity) App.getActivity());
            isRob = false;
        });
    }

    // 已经认证，进行检测权限限制
    private void permissionAuth() {
        LoadingDialog.show((FragmentActivity) App.getActivity(), "授权检测中，请稍后");
        PermissionUtil.checkAVPermission(App.getActivity(), new PermissionListener() {
            @Override
            public void success() {
                permissionAuth = true;
                PToast.showShort("授权检测成功，您可以畅快聊天啦!");
                LoadingDialog.closeLoadingDialog();
            }

            @Override
            public void fail() {
                PToast.showShort("授权检测失败，无法进行抢聊，请到应用设置页进行相机手动授权!");
                LoadingDialog.closeLoadingDialog();
            }
        });
    }

    @Override
    public int getRecycleViewItemType(int position) {
        return 0;
    }

    class MyViewHolder {
        ImageView user_head, btn_rob, user_vip;
        TextView user_nick, tv_amount;

        public MyViewHolder(BaseRecyclerViewHolder convertView) {
            initView(convertView);
        }

        private void initView(BaseRecyclerViewHolder convertView) {
            user_head = convertView.findViewById(R.id.user_head);
            user_nick = convertView.findViewById(R.id.user_nick);
            btn_rob = convertView.findViewById(R.id.btn_rob);
            tv_amount = convertView.findViewById(R.id.tv_amount);
            user_vip = convertView.findViewById(R.id.user_vip);
        }
    }
}